import { useCallback, useEffect, useState } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
// import {} from '../service'
import { Form, message } from 'antd'
import moment from 'moment'
import { useRecoilValue } from 'recoil'
import { getRandomString, isNullArray, isNullData, isSuccess } from '@/utils'
import { CheckHooks, VariableList } from '../data'
import { getWord, WordList } from '@/services/common'
import { TableInfo } from '@/pages/ReportDetails/data'
import {
  escalationApplyUpdate,
  getDataTaskDetail,
  getInjuryInformation,
  addEventHandle,
  editEventHandle,
  deleteEventHandle,
  getOrganization,
} from '../service'
import { IPressure, IVariableSort } from '@/@types/common'
import { userInfo } from '@/store/userInfo'

interface ParamsRout extends TableInfo {
  task: string[]
  isShowBtn: string
  readyOnly: boolean
  zkjType: string
}
export default (): CheckHooks => {
  const userinfo = useRecoilValue(userInfo)
  const parasm = useLocation()
  const navigate = useNavigate()
  const { task: paramstask, reportStatus, dataId, isShowBtn, readyOnly, zkjType } = parasm.state as ParamsRout
  const [formObj] = Form.useForm()
  const [varableForm] = Form.useForm()
  const [applyReasonForm] = Form.useForm()
  // 当前选中任务
  const [task, setTask] = useState<string[]>(paramstask)

  // modal
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false)
  // 病区
  const [wordList, setWordList] = useState<WordList[]>([])
  // 存放当前选中病区
  const [selectWord, setSelectWord] = useState<number | undefined>(dataId)
  const [isEdit, setIsEdit] = useState<boolean>(false)
  // 变量下拉框
  const [variable, setVariable] = useState<VariableList[]>([
    {
      value: 1,
      label: '变量数据',
    },
    {
      value: 2,
      label: '指标数据',
    },
  ])

  // 存储编辑的信息
  const [editInfo, setEditInfo] = useState<IPressure>()
  // 存放变量指标数据
  const [varableTableList, setVariableList] = useState<IVariableSort[]>([])
  // 控制modal
  const [visible, setVisible] = useState<boolean>(false)
  // 事件数据
  const [eventList, setEventList] = useState<IPressure[]>([])
  // 变量loading
  const [varableLoading, setVariableLoading] = useState<boolean>(false)

  // 存放变量指标下拉框
  const [tag, setTag] = useState<number>(1)

  // 医院管理员存储病区级联关系
  const [wardList, setWardList] = useState<any>([])
  // 压疮病例数变量id, 该变量的数量要和底部事件
  const [pressureId, setPressureId] = useState<string>('')

  // 获取地区
  const getWords = useCallback(async () => {
    const res = await getWord({
      hospitalCode: userinfo.hospitalCode,
      dataReportYear: paramstask[0],
      dataReportQuarter: paramstask[1],
    })
    if (isNullData(res) && res.data && isNullArray(res.data)) {
      setWordList(res.data)
      // setSelectWord(res.data[0].dataId)
    } else {
      setWordList([])
    }
  }, [])

  // 任务下拉框变化时触发
  const handleTaskChange = useCallback((e: string[]) => {
    setTask(e)
  }, [])

  // 病区发生变化时触发
  const handleWordChange = useCallback((e: number) => {
    setSelectWord(e)
  }, [])

  const getInjuryInfo = useCallback(async () => {
    const res = await getInjuryInformation({
      dataId: selectWord!,
      type: zkjType,
    })
    if (isNullData(res) && res.data && isNullArray(res.data)) {
      setEventList(res.data)
    } else {
      setEventList([])
    }
  }, [selectWord, zkjType])

  // 递归函数，将原始数据转换为 Cascader 数据结构
  const transformDataCatalogue = (items: any) =>
    items.map((item: any) => {
      const dis = item.type === '20' && item.endemicAreaVos.length === 0
      const cascaderItem: any = {
        label: item.unit,
        value: item.id.toString(),
        disabled: dis,
      }
      if (item.endemicAreaVos.length > 0) {
        cascaderItem.children = transformDataCatalogue(item.endemicAreaVos)
      }
      return cascaderItem
    })
  // 查询变量信息
  const getVarableList = useCallback(async () => {
    varableForm.resetFields()
    setVariableLoading(true)
    const res = await getDataTaskDetail({
      dataId: selectWord!,
    })
    console.log('🚀 ~ file: index.ts:135 ~ getVarableList ~ res:', res.data?.sortPlatformVos)

    if (isNullData(res) && res.data && isNullArray(res.data)) {
      setVariableList(res.data.sortPlatformVos)
      if (res.data.flag) {
        await getInjuryInfo()
        // 保存压疮变量的id
        setPressureId(res.data.pressureId)
        if (userinfo.hospitalCode && userinfo.accountType >= 30) {
          // 如果登录人信息有hospitalCode, 且角色医院及其下属
          const res = await getOrganization({
            hospitalCode: userinfo.hospitalCode,
          })
          setWardList(transformDataCatalogue(res.data.endemicAreaVos))
        }
      }
    } else {
      setVariableList([])
    }
    setVariableLoading(false)
  }, [selectWord])

  // 变量下拉框
  const handleVaribleChange = useCallback((e: number) => {
    setTag(e)
  }, [])

  // 查看
  const handlePreview = (list: IPressure) => {
    setEditInfo(list)
    const happenArea = list.happenAreaId.split('/')
    formObj.setFieldsValue({
      ...list,
      happenArea,
      admissionTime: moment(list.admissionTime),
      happenDate: moment(list.happenDate),
    })
    setVisible(true)
    setIsEdit(true)
  }

  // 取消关闭回调
  const handleCancel = () => {
    formObj.resetFields()
    setVisible(false)
    setIsEdit(false)
    setEditInfo(undefined)
  }

  // 编辑事件内容数据
  const editEventList = (editInfo: IPressure, index: number, res: IPressure) => {
    // 如果有isInsert说明是新增的数据
    if (editInfo.isInsert) {
      const newlist = [...eventList]
      newlist[index] = {
        ...res,
        admissionTime: moment(res.admissionTime).format('YYYY-MM-DD'),
        happenDate: moment(res.happenDate).format('YYYY-MM-DD'),
        isInsert: editInfo.isInsert,
        id: editInfo.id,
      }
      setEventList(newlist)
      handleCancel()
    } else {
      // 不是新增的数据  存修改的值就行
      const newlist = [...eventList]
      newlist[index] = {
        ...res,
        admissionTime: moment(res.admissionTime).format('YYYY-MM-DD'),
        happenDate: moment(res.happenDate).format('YYYY-MM-DD'),
        id: editInfo.id,
      }
      setEventList(newlist)
      handleCancel()
    }
  }

  // // 处理事件内容数据
  // const addEventList = (res: IPressure, editInfo?: IPressure) => {
  //   // 如果有id说明是编辑
  //   if (editInfo?.id) {
  //     const index = eventList.findIndex((item) => item.id === editInfo.id)
  //     editEventList(editInfo, index, res)
  //   } else {
  //     // 没有id说明单纯的添加一条数据
  //     setEventList([
  //       ...eventList,
  //       {
  //         ...res,
  //         id: getRandomString(),
  //         admissionTime: moment(res.admissionTime).format('YYYY-MM-DD'),
  //         happenDate: moment(res.happenDate).format('YYYY-MM-DD'),
  //         isInsert: 'Y',
  //       },
  //     ])
  //     handleCancel()
  //   }
  // }

  // modal确定
  const handleOk = async (isHCancel: boolean) => {
    // 直接点确定
    const formValue = await formObj.validateFields()
    // 校验通过
    if (formValue) {
      if (isEdit) {
        const params = {
          dataId: selectWord,
          ...editInfo,
          ...formValue,
          happenDate: formValue.happenDate.format('YYYY-MM-DD'),
          admissionTime: formValue.admissionTime.format('YYYY-MM-DD'),
          happenArea: formValue.happenArea.at(-1),
        }
        const res = await editEventHandle(params)
        if (isNullData(res) && isSuccess(res.data)) {
          message.success('编辑成功')
          await getInjuryInfo()
        } else {
          message.error(res.data.message || '编辑失败')
          return
        }
        handleCancel()
      } else {
        const params = {
          dataId: selectWord,
          ...formValue,
          happenDate: formValue.happenDate.format('YYYY-MM-DD'),
          admissionTime: formValue.admissionTime.format('YYYY-MM-DD'),
          happenArea: formValue.happenArea.at(-1),
        }
        const res = await addEventHandle(params)
        if (isNullData(res) && isSuccess(res.data)) {
          message.success('新增成功')
          await getInjuryInfo()
          if (isHCancel) {
            // 直接点击确定
            handleCancel()
          } else {
            // 确认并继续填写
            formObj.resetFields()
          }
        } else {
          message.error(res.data.message || '新增失败')
        }
      }
      // addEventList(formValue, editInfo)
    }
  }

  // 删除回调
  const deleteHandle = async (record: IPressure) => {
    const params = {
      dataId: selectWord,
      ...record,
    }
    const res = await deleteEventHandle(params)
    if (isNullData(res)) {
      message.success('删除成功')
      await getInjuryInfo()
    }
  }

  // 关闭申请修改modal
  const handleCancelModal = () => {
    setIsModalOpen(false)
    applyReasonForm.resetFields()
  }

  // 判断事件内容是否对应上
  const isCorrespond = (value: number | undefined) => {
    if (value !== undefined) {
      return value === eventList.length
    }
    const info = varableTableList.find((item) => item.variablePlatformVos.find((val) => val.id === pressureId))
    const varable = info?.variablePlatformVos.find((item) => item.id === pressureId)
    if (varable) {
      return +varable!.variableValue === eventList.length
    }
    return true
  }

  const findVariable = (id: string) => {
    for (const item of varableTableList) {
      const variable = item.variablePlatformVos.find((variableItem) => variableItem.id === id)
      if (variable) {
        return variable
      }
    }
    return null
  }
  // 申请修改
  const handleSubmit = async () => {
    const res = await varableForm.validateFields()
    // 获取压疮id对应的name
    const pressure = findVariable(pressureId)
    if (pressure && !isCorrespond(res[pressure?.variableName])) {
      return message.warning('事件内容与患者压力性损伤个数对应不上，请重新输入！')
    }
    const variableData = varableTableList
      .map((item) =>
        item.variablePlatformVos.map((val) => {
          if (res[val.id]) {
            console.log('val🚀🚀🚀🚀', val)
            return {
              id: val.id,
              variableId: val.variableValueId,
              variableValue: res[val.variableName],
              oldVariableValue: val.variableValue,
            }
          }
          return null
        }),
      )
      .flat()
    const newlist = variableData.filter((item) => !!item)
    console.log('newlist🚀🚀🚀🚀', newlist)
    if (!isNullArray(newlist)) {
      return message.warning('请做出修改！')
    }
    // console.log('res查🚀🚀🚀🚀', res)
    setIsModalOpen(true)
  }

  // 申请修改接口
  const applyReasonAdd = async () => {
    const res = await varableForm.validateFields()
    const applyReasonRes = await applyReasonForm.validateFields()
    if (applyReasonRes) {
      const variableData = varableTableList
        .map((item) =>
          item.variablePlatformVos.map((val) => {
            if (res[val.id]) {
              return {
                id: val.id,
                variableId: val.variableValueId,
                variableValue: res[val.variableName],
                oldVariableValue: val.variableValue,
              }
            }
            return null
          }),
        )
        .flat()

      const respone = await escalationApplyUpdate({
        dataId: selectWord,
        applyReason: applyReasonRes.applyReason,
        variableData: variableData.filter((item) => !!item),
        injuryInformationDataList: eventList.map((item) => item.id),
        happenArea: selectWord,
      })
      if (isNullData(respone) && respone.data && isSuccess(respone.data)) {
        message.success('修改成功')
        handleCancelModal()
        navigate(-1)
      } else {
        message.error(respone.data?.message)
      }
    }
  }

  // 勾选框change
  const handleVarableChange = (fatherId: string, id: string) => {
    const newlist = [...varableTableList]
    const info = newlist.find((item) => item.id === fatherId)
    const varable = info?.variablePlatformVos.find((item) => item.id === id)
    if (varable) {
      varable.flag = !varable.flag
    }
    setVariableList(newlist)
  }

  // 申请修改事件内容弹窗
  const setShowEventModal = () => {
    setVisible(true)
  }

  useEffect(() => {
    getWords()
  }, [])

  useEffect(() => {
    if (selectWord) {
      getVarableList()
    }
  }, [selectWord])

  return {
    task,
    handleTaskChange,
    wordList,
    handleWordChange,
    variable,
    varableTableList,
    eventList,
    handleSubmit,
    handleVaribleChange,
    tag,
    selectWord,
    varableLoading,
    handlePreview,
    deleteHandle,
    varableForm,
    IndicatorsModal: {
      formObj,
      visible,
      handleOk,
      handleCancel,
      onlyLook: readyOnly,
      wardList,
    },
    isEdit,
    setShowEventModal,
    handleVarableChange,
    applyReasonForm,
    applyReasonAdd,
    isModalOpen,
    handleCancelModal,
    reportStatus,
    isShowBtn,
    readyOnly,
  }
}
